import React from 'react';
import { useLatest } from '@/hooks';

/**
 * DOM 变化监听
 */
function useResizeObserver(elememtRef, callback) {
    const callbackRef = useLatest(callback);

    React.useEffect(() => {
        if (elememtRef.current) {
            const resizeObserver = new window.ResizeObserver((entries) => {
                for (let entry of entries) {
                    callbackRef.current(entry);
                }
            });

            resizeObserver.observe(elememtRef.current);

            return () => resizeObserver.disconnect();
        }
    }, []);
}

export default useResizeObserver;
